import { ApiCall, WsConnection } from "tsrpc";
import { ReqJoin, ResJoin } from "../../../tsrpc/shared/protocols/room/PtlJoin";
import { rs } from "../../../RoomServiceEntra";
import { RoomJoinComp } from "../../../module/room/system/RoomJoinSystem";
import { ServiceType } from "../../../tsrpc/shared/protocols/RoomServiceProto";

export default async function (call: ApiCall<ReqJoin, ResJoin>) {
    // TODO
    if (!rs.RoomServiceModel.rooms.has(call.req.roomId)) {
        call.error("没有找到房间",{code:"ROOM_NO_EXIST"})
        return;
    }
    const room = rs.RoomServiceModel.rooms.get(call.req.roomId);
    if (room == null) { return; }

    if (room.RoomModel.password.length != 0) {//房间需要密码
        if (room.RoomModel.password != call.req.password) {
            call.error("密码错误", {code:"Passwrod Error"})
            return;
        }
    }
    
    const comp = room.add(RoomJoinComp);
    comp.uId = call.req.uId;
    comp.conn = call.conn as WsConnection<ServiceType>;
}